package chinaums2

import (
    "fmt"
	"errors"
	"github.com/astaxie/beego"
)

type PayReq struct {
	MerId       string  `form:"MerId"`
	OrderNo     string  `form:"OrderNo"`
	OrderAmount float32 `form:"OrderAmount"`
	CurrCode    string  `form:"CurrCode"`
	OrderType   string  `form:"OrderType,omitempty"`
	CallBackUrl string  `form:"CallBackUrl"`
	BankCode    string  `form:"BankCode,omitempty"`
	LangType    string  `form:"LangType,omitempty"`
	BuzType     string  `form:"BuzType,omitempty"`
	Reserved01  string  `form:"Reserved01,omitempty"`
	Reserved02  string  `form:"Reserved02,omitempty"`
	SignMsg     string  `form:"SignMsg"`
}

type PayRsp struct {
    OrderNo     string  `form:"OrderNo"`
    PayNo       string  `form:"PayNo"`
	PayAmount   float32 `form:"PayAmount"`
	CurrCode    string  `form:"CurrCode"`
	SystemSSN   string  `form:"SystemSSN"`
	RespCode    string  `form:"RespCode"`
	SettDate    string  `form:"SettDate"`
    Reserved01  string  `form:"Reserved01,omitempty"`
	Reserved02  string  `form:"Reserved02,omitempty"`
	SignMsg     string  `form:"SignMsg"`
}


func MicroAppPay(account,terminal,noticeUrl,orderId,currency,amount,openId,firstName,lastName,ipAddr,productName ,key string)(payInfo string, err error){
	req := new(PayReq)
	req.Account = account
	req.Terminal = terminal
	req.NoticeUrl = noticeUrl
	req.Methods = "WX"
	req.OrderNumber = orderId
	req.OrderCurrency = currency
	req.OrderAmount = amount
	req.CustomerId = openId
	req.BillingFirstName = firstName
	req.BillingLastName = lastName
	req.BillingEmail = openId + "@dhfapp.com"
	req.BillingCountry = "CN"
	req.BillingIp = ipAddr
	req.ProductName = productName
	req.BackUrl = "N/A"
	req.SignValue = makeOrderSign(req, key)
	reqURL := "https://secure.oceanpayment.com/gateway/directservice/pay"
	sdk := NewSDK(reqURL)
	rsp := new(PayRsp)
	_, err = sdk.Request(req, rsp)
	if err != nil {
		beego.Debug("OceanPayment MicroAppPay err:", err.Error())
		return
	}
	if rsp.PaymentStatus == "0" {
	   err = errors.New(rsp.PaymentDetails)
	}
	payInfo = rsp.PaymentBankInfo
	return
}

func makeOrderSign(payReq *PayReq, key string) string {
	str := payReq.Account
	str += payReq.Terminal
	str += payReq.OrderNumber
	str += payReq.OrderCurrency
	str += payReq.OrderAmount
	str += payReq.BillingFirstName
	str += payReq.BillingLastName
	str += payReq.BillingEmail
	str += key
	return fmt.Sprintf("%x", sHA256([]byte(str)))
}
